// util.js
import CryptoJS from '@/external/CryptoJS.js';
export default {
	generateSign(params, token) {
		// 将参数按字母排序并拼接成字符串
		// console.log("参数", params)
		let sortedParams = Object.keys(params).sort().map(key => `${key}=${params[key]}`).join('&');
		// 将排序后的参数字符串与 token 拼接
		// console.log(sortedParams)
		let signString = sortedParams + '&' + token;
		// 使用 MD5 进行加密
		// console.log(signString)
		return CryptoJS.MD5(signString).toString()
	},

	requestWithSign(params, options) {
		let url = 'https://huishou.68699.cn/app/index.php';
		// 生成签名
		var token = options?options.token:""
		let sign = this.generateSign(params, token);
		// 将签名参数添加到请求参数中
		let obj = {
			sign: sign,
			i: 2,
			t: 0,
			v: '2.7.4',
			from: 'wxapp',
			c: 'entry',
			a: 'wxapp',
			m: 'wjyk_recycle',
		}
		uni.showLoading({
		    title: "加载中..."
		});
		// console.log("sign:", sign)
		let requestParam = Object.assign({}, obj, params); //若出现同名参数，则后面对象中的会替代前面对象中的值
		// 发起请求
		var header = {
		"Content-Type": "application/json",
		"Content-Type": "application/x-www-form-urlencoded"
	}
		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				data: requestParam,
				header: options?options.header:header,
				method: options?options.method:"get",
				success: (result) => {
					if (result.statusCode !== 200) {
						return reject(result);
					}
					uni.hideLoading();
					let data = result.data;
					resolve(data);
				},
				fail: (error) => {
					reject(error);
				}
			});
		});
	},
	uploadImg(filePath,name){
		var url = "https://huishou.68699.cn/app/index.php?i=2&c=entry&a=wxapp&do=upload&m=wjyk_recycle"
		uni.showLoading({
		    title: "上传中..."
		});
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: url,
				filePath: filePath,
				name:name,
				success: (result) => {
					console.log("结果",result)
					if (result.statusCode !== 200) {
						return reject(result);
					}
					uni.hideLoading();
					let data = result.data;
					resolve(data);
				},
				fail: (error) => {
					reject(error);
				}
			});
		});
	}
};